package com.cdd.permission.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cdd.permission.mapper.PermissionMapper;
import com.cdd.permission.service.PermissionService;
import com.common.entity.Permission;
import com.common.entity.User;
import com.common.untils.CommonResult;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author lenovo
 * @version 1.0
 * @since 2022-08-31  20:45:50
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;

    //根据用户id查询用户具有的权限
    @Override
    public List<String> selectselectPermission(String userId) {
        return permissionMapper.selectPermission(userId);
    }

    //获取权限--二级菜单
    @Override
    public CommonResult selectPermission(String token) {
        //从redis中获取token
        String s = redisTemplate.opsForValue().get(token);
        //将获取到的token转为map
        Map map = JSON.parseObject(s, Map.class);
        //获取token中的值
        JSONObject user = (JSONObject) map.get("user");
        String userId = user.getString("userId");
        //根据userId查询全部的权限
        List<Permission> permissionList = permissionMapper.selectLeftPermission(userId);
        //设置层级关系
        List<Permission> firstMenus = new ArrayList<>();

        for (Permission first : permissionList) {
            //找一级菜单
            if (first.getPid().equals("0")) {
                firstMenus.add(first);
            }
        }

        //为一级菜单设置二级菜单
        for (Permission first : firstMenus) {
            //根据一级菜单id 查询 该菜单得二级菜单。如果出现不确定有几级菜单 那么我们可以使用方法得递归调用
            first.setChildren(findChildren(permissionList, first.getId()));
        }

        return new CommonResult(2000, "查询成功", firstMenus);

    }
    //查询所有的权限
    @Override
    public List<Permission> selectAllPermission() {
        QueryWrapper wrapper=new QueryWrapper();
        wrapper.eq("is_deleted",0);
        List list = permissionMapper.selectList(wrapper);
        return list;
    }

    //方法递归
        private List<Permission> findChildren (List < Permission > permissionList, String id){
            List<Permission> children = new ArrayList<>();
            for (Permission p : permissionList) {
                if (p.getPid().equals(id)) {
                    children.add(p);
                }
            }
            for (Permission child : children) {
                child.setChildren(findChildren(permissionList, child.getId()));
            }
            return children;

        }

    }

